package cn.wizzer.app.user.util;

import cn.wizzer.app.user.modules.models.constant.UserConstant;
import cn.wizzer.app.user.modules.models.enums.EquipmentEnum;
import cn.wizzer.framework.base.Result;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import redis.clients.jedis.ScanParams;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 22099
 */
//假冒伪劣tokenUtil
@IocBean(singleton = false, name = "tokenUtil")
public class TokenUtilImpl extends TokenUtil {

    @Inject
    RedisService redisService;
    @Inject
    Ioc ioc;

    static long oneHour = 1000 * 60 * 60;
    static long oneDay = 1000 * 60 * 60 * 24;

    public String generateToken(Date date, String appid, EquipmentEnum equipment) {
        if (equipment == null) {
            equipment = EquipmentEnum.MOBILE;
        }
        String token = null;
        try {
            token = ioc.get(TokenUtil.class).generateToken(date, appid);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            Result.breakWith(e.toString());
        }
        //验证已登录设备中相同设备以做离线处理
        ScanParams scanParams = new ScanParams();
        scanParams.match(UserConstant.getSampleRedisKeyToken(appid,equipment));
        scanParams.count(Integer.MAX_VALUE);
        List<String> keys = redisService.scan("0", scanParams).getResult();
        if (keys.size()>0){
            //除当前token以外全部失效
            redisService.del(keys.stream().collect(Collectors.joining(",")).split(","));
        }
        //设置过期时间到redis
        String redisKeyToken = UserConstant.getRedisKeyToken(appid, token, equipment);
        redisService.set(redisKeyToken, date.getTime()+"");
        return token;
    }

    public boolean verifyToken(String appid, String token, EquipmentEnum equipment) {
        if (equipment == null) {
            equipment = EquipmentEnum.MOBILE;
        }
        String redisKeyToken = UserConstant.getRedisKeyToken(appid, token, equipment);
        String expireTime = redisService.get(redisKeyToken);
        //未登录
        if (Strings.isEmpty(expireTime)) {
            return false;
        }
        long current = System.currentTimeMillis();
        long value = new Long(expireTime) - current;
        //登录超时
        if(value<=0){
            return false;
        }
        //重新设置过期时间
        else if (value <= oneHour) {
            redisService.set(redisKeyToken, current + oneDay+"");
        }
        return true;
    }
}
